<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    :width="width >= 600 ? 600 : '100%'"
    draggable
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { getDeviceModel, addDeviceModel, updateDeviceModel } from '@/apis/asset/device/model'
import { type ColumnItem, GiForm } from '@/components/GiForm'
import { useResetReactive } from '@/hooks'
import { useDict } from '@/hooks/app'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改设备型号' : '新增设备型号'))
const formRef = ref<InstanceType<typeof GiForm>>()

const [form, resetForm] = useResetReactive({
  // todo 待补充
})

const columns: ColumnItem[] = reactive([
  {
    label: '名称',
    field: 'name',
    type: 'input',
    span: 24,
    rules: [{ required: true, message: '请输入名称' }]
  },
  {
    label: '品牌id',
    field: 'brandId',
    type: 'tree-select',
    span: 24,
    rules: [{ required: true, message: '请输入品牌id' }]
  },
  {
    label: '类型id',
    field: 'typeId',
    type: 'tree-select',
    span: 24,
    rules: [{ required: true, message: '请输入类型id' }]
  },
  {
    label: '状态（1：启用；2：禁用）',
    field: 'status',
    type: 'input',
    span: 24,
    rules: [{ required: true, message: '请输入状态（1：启用；2：禁用）' }]
  },
  {
    label: '是否为系统内置数据',
    field: 'isSystem',
    type: 'input',
    span: 24,
  },
])

// 重置
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

// 保存
const save = async () => {
  try {
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false
    if (isUpdate.value) {
      await updateDeviceModel(form, dataId.value)
      Message.success('修改成功')
    } else {
      await addDeviceModel(form)
      Message.success('新增成功')
    }
    emit('save-success')
    return true
  } catch (error) {
    return false
  }
}

// 新增
const onAdd = async () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  const { data } = await getDeviceModel(id)
  Object.assign(form, data)
  visible.value = true
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss"></style>
